package org.example.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class CuratorLockTest {
    public static void main(String[] args) {
        /**
         * CuratorFramework client: Curator 客户端
         * String path: 加锁节点路径
         */
        InterProcessMutex mutex1 = new InterProcessMutex(getCuratorFramework(), "/lock");
        InterProcessMutex mutex2 = new InterProcessMutex(getCuratorFramework(), "/lock");
        new Thread(() -> {
            try {
                // 阻塞直到获取锁（可能永久阻塞）
                mutex1.acquire();
                System.out.println("线程" + Thread.currentThread().getName() + " 获取到锁...");
                mutex1.acquire();
                System.out.println("线程" + Thread.currentThread().getName() + " 再次获取到锁...");
                Thread.sleep(3 * 1000);
                mutex1.release();
                System.out.println("线程" + Thread.currentThread().getName() + " 释放锁...");
                mutex1.release();
                System.out.println("线程" + Thread.currentThread().getName() + " 再次释放锁...");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }).start();

        new Thread(() -> {
            try {
                mutex2.acquire();
                System.out.println("线程" + Thread.currentThread().getName() + " 获取到锁...");

                mutex2.acquire();
                System.out.println("线程" + Thread.currentThread().getName() + " 再次获取到锁...");
                Thread.sleep(3 * 1000);
                mutex2.release();
                System.out.println("线程" + Thread.currentThread().getName() + " 释放锁...");
                mutex2.release();
                System.out.println("线程" + Thread.currentThread().getName() + " 再次释放锁...");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }).start();
    }

    private static CuratorFramework getCuratorFramework() {
        CuratorFramework curatorFramework = CuratorFrameworkFactory.builder()
                .connectString("47.108.48.236:2182")
                .sessionTimeoutMs(300000)
                .connectionTimeoutMs(300000)
                .retryPolicy(new ExponentialBackoffRetry(300000, 4)) // 重试策略
                .build();
        // 启动客户端
        curatorFramework.start();
        return curatorFramework;
    }
}
